package com.example.questionsystem.modules.qu.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws IOException {
        // 1. 创建数据目录
        String currentDir = System.getProperty("user.dir");
        Path dataDir = Paths.get(currentDir, "data");
        if (!Files.exists(dataDir)) {
            Files.createDirectories(dataDir);
            System.out.println("数据目录已创建: " + dataDir.toAbsolutePath());
        }
        // 获取所有已存在的表名
        List<String> existingTables = jdbcTemplate.queryForList(
            "SELECT name FROM sqlite_master WHERE type='table'", String.class
        );

        // 遍历预定义的表
        for (Map.Entry<String, String> entry : TableDefinitions.TABLES.entrySet()) {
            String tableName = entry.getKey();
            String createSql = entry.getValue();

            if (!existingTables.contains(tableName)) {
                jdbcTemplate.execute(createSql);
                System.out.println("Created table: " + tableName);
            }
        }
    }
}